package com.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.config.HsProperty;
import com.config.SourceDataProperty;
import com.dto.*;
import com.netty.MyClient;
import com.utils.HsEncodeUtils;
import com.utils.ShopInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduledWork {

    @Resource
    private SourceDataProperty sourceDataProperty;

    @Resource
    private HsProperty hsProperty;

    private static String sourceToken;


    private static long tokenExpire = 0L;


    @Resource
    private HsEncodeUtils hsEncodeUtils;




    @Scheduled(fixedDelay = 5000, initialDelay = 1000 * 10)
    public void getSourceData() {
        log.info("----------开始推送数据-------");
        String token = "";
        long now = System.currentTimeMillis();
        if (tokenExpire > now) {
            token = sourceToken;
        } else {
            token = getToken();
        }
//        log.info("使用token->{}， 请求车辆实时数据->{}");
        //访问
        if (token == null) {
            log.info("token is null , tokenExpire->{}, now->{}", tokenExpire, now);
            return;
        }
        if (hsProperty.isStartConnect()) {
            if (MyClient.mychannel == null || !MyClient.mychannel.isActive()) {
                log.error("通道不存在 或者 通道不活跃, 无法发送消息");
                return;
            }
        }

        SourceDataCarLocationApiQry sourceDataCarLocationApiQry = new SourceDataCarLocationApiQry();
        String deviceIds = ShopInfo.deviceIds.keySet().stream().collect(Collectors.joining(","));
        sourceDataCarLocationApiQry.setDeviceId(deviceIds);
        sourceDataCarLocationApiQry.setLingxtoken(token);


        String locationJson = HttpUtil.post(sourceDataProperty.getUrl(), JSONUtil.toJsonStr(sourceDataCarLocationApiQry));
        SourceCarLocationCO sourceCarLocationCO = JSONUtil.toBean(locationJson, SourceCarLocationCO.class);
        if (sourceCarLocationCO.getCode() == 1) {

            List<SourceCarLocationDto> locationDtos = sourceCarLocationCO.getData();
//            log.info("本次请求到的定位信息->{}", JSONUtil.toJsonStr(locationDtos));
            //发送channel
            for (SourceCarLocationDto sourceCarLocationDto : locationDtos) {
//                if (sourceCarLocationDto.getOnline() == 1 && sourceCarLocationDto.getStatus_jt808() == 3) {
                    ByteBuf byteBuf = hsEncodeUtils.packLocationMessage(sourceCarLocationDto);
                    if (byteBuf == null) {
                        continue;
                    }
                    if (MyClient.mychannel != null && MyClient.mychannel.isActive()) {
                        log.info("设备->{},名称->{}, 定位时间->{}, 经度->{}, 纬度->{} ,速度->{},方向->{}, 发送定位报文->【{}】",
                                sourceCarLocationDto.getTid(),
                                ShopInfo.deviceIds.getOrDefault(sourceCarLocationDto.getTid(), ""),
                                sourceCarLocationDto.getGpstime(),
                                sourceCarLocationDto.getLng(),
                                sourceCarLocationDto.getLat(),
                                sourceCarLocationDto.getSpeed(),
                                sourceCarLocationDto.getDirection(),
                                ByteBufUtil.hexDump(byteBuf));
                        MyClient.mychannel.writeAndFlush(byteBuf);
                    }

//                }
            }
        } else {
            log.error("请求定位信息失败：{}", JSONUtil.toJsonStr(sourceCarLocationCO));
        }


    }



    @Scheduled(fixedDelay = 1000 * 30, initialDelay = 5000)
    public void checkChannel() {

        try {
            if (MyClient.mychannel != null && !MyClient.mychannel.isActive()) {
                log.info("开启重连.........");
                MyClient.reconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }







    private String getToken() {
        String post = null;
        try {
            SourceDataTokenApiQry sourceDataTokenApiQry = new SourceDataTokenApiQry();
            sourceDataTokenApiQry.setAccount(sourceDataProperty.getUsername());
            String password = DigestUtil.md5Hex(DigestUtil.md5Hex(sourceDataProperty.getPassword()) + DigestUtil.md5Hex(sourceDataProperty.getUsername()));
            sourceDataTokenApiQry.setPassword(password);
            sourceDataTokenApiQry.setApitoken(sourceDataProperty.getApiToken());


            post = HttpUtil.post(sourceDataProperty.getUrl(), JSONUtil.toJsonStr(sourceDataTokenApiQry));
            SourceTokenCO sourceTokenCO = JSONUtil.toBean(post, SourceTokenCO.class);
            if (sourceTokenCO != null && sourceTokenCO.getCode() == 1) {
                sourceToken = sourceTokenCO.getToken();
                tokenExpire = System.currentTimeMillis() + 25 * 60 * 1000;
                return sourceToken;
            } else {
                log.error("获取返回的token失败:{}", JSONUtil.toJsonStr(sourceTokenCO));
                return null;
            }
        } catch (Exception e) {
            log.error("访问token接口出错：",e);
            return null;
        }

//        System.err.println(post);
    }


}
